using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Media;

namespace TicTacToe.Core
{
    public class Player
    {
        public string Name { get; private set; }
        public Color Color { get; private set; }

        readonly string mId;
        public string ID
        {
            get { return mId; }
        }

        protected internal virtual void OnTurn(TicTacToeGame game)
        { }

        internal void BeginOnTurn(TicTacToeGame game)
        {
            Task.Factory.StartNew(() => OnTurn(game));
        }

        public override string ToString()
        {
            return Name;
        }

        public static bool IsValidName(string nameStr)
        {
            return Regex.IsMatch(nameStr, @"^[\w\[\]][\w \[\]]{0,38}[\w\[\]]?$");
        }

        public Player(string name, Color color)
            : this(name, color, Guid.NewGuid().ToString())
        {
        }

        public Player(string name, Color color, string id)
        {
            if (!IsValidName(name))
                throw new ArgumentException("Given name is invalid", "name");

            Name = name;
            Color = color;
            mId = id;
        }

        public static bool operator !=(Player p1, Player p2)
        {
            return !(p1 == p2);
        }

        public static bool operator ==(Player p1, Player p2)
        {
            try
            {
                return p1.Color == p2.Color &&
                       p1.Name == p2.Name &&
                       p1.ID == p2.ID;
            }
            catch (NullReferenceException)
            {
                return false;
            }
        }

        public override bool Equals(object obj)
        {
            if (obj is Player)
                return (obj as Player) == this;
            else
                return base.Equals(obj);
        }
    }
}